﻿using System;
using System.Linq;
using Gumini.JulaDB.Enums;
using Gumini.JulaDB.Provider;
using Irony.Parsing;

namespace Gumini.JulaDB.Parser
{
    public static class ParserExtensions
    {
        public static SourcePosition GetPosition(this ParseTreeNode node)
        {
            return new SourcePosition(node.Span.Location);
        }

        public static ParseTreeNode GetSubNode(this ParseTreeNode node, BnfTerm term)
        {
            if (node == null)
                return null;
            return node.ChildNodes.Where(n => n.Term == term).FirstOrDefault();
        }

        public static string GetName(this ParseTreeNode node, SqlGrammar grammar, bool allowCompositeNames = false)
        {
            if (node.ChildNodes.Select(n => n.Term).
                Where(t => t != grammar.Id_simple).Any())
                throw new InvalidOperationException("Expected list of simple ids.");

            var fullName = string.Join(".", node.ChildNodes.Select(n => n.Token.Text).ToArray()); 
            if (!allowCompositeNames)
            {
                if (node.ChildNodes.Count != 1 )
                    throw new JulaDbException(ErrorCode.InvalidIdentifier, node.GetPosition(), "A simple name expected, got '{0}'.", fullName);
                return fullName;
            }
            else
            {
                if (node.ChildNodes.Count > 2 || node.ChildNodes.Count < 1)
                    throw new JulaDbException(ErrorCode.InvalidIdentifier, node.GetPosition(), "A simple or composite name expected, got '{0}'.", fullName);
                return fullName;
            }
        }
    }
}
